package com.cj.webapp_Start.sp_network.encryption;


import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

public class RSAUtil {

    /**
     * 加密算法RSA
     */
    public static final String KEY_ALGORITHM = "RSA";
    /**
     * 填充模式(jdk默认)
     */
    public static final String PADDING = "RSA/NONE/PKCS1Padding";
    /**
     * 签名算法
     */
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
    /**
     * 获取公钥的key
     */
    public static final String PUBLIC_KEY = "RSAPublicKey";
    /**
     * 获取私钥的key
     */
    public static final String PRIVATE_KEY = "RSAPrivateKey";
    /**
     * 最大加密明文大小
     */
    public static final int MAX_ENCRYPT_BLOCK = 117;
    /**
     * 最大解密密文大小
     */
    public static final int MAX_DECRYPT_BLOCK = 128;



    /**
     * 生成Base64秘钥对
     *
     * @return
     * @throws Exception
     */

    public static Map<String, String> genKeyPair() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        Map<String, String> keyMap = new HashMap<>(2);
        keyMap.put(PUBLIC_KEY,
                Base64.encodeToString(publicKey.getEncoded(), Base64.NO_WRAP));

        keyMap.put(PRIVATE_KEY, Base64.encodeToString(privateKey.getEncoded(), Base64.NO_WRAP));
        return keyMap;
    }

    /**
     * 私钥签名
     *
     * @param data
     * @param base64PrivateKey
     * @return
     * @throws Exception
     */

    public static String sign(String data, String base64PrivateKey) throws Exception {
        byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);

        PrivateKey privateKey = string2PrivateKey(base64PrivateKey);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(privateKey);
        signature.update(dataBytes);

        byte[] signBytes = signature.sign();
        return Base64.encodeToString(signBytes, Base64.NO_WRAP);
    }

    /**
     * 公钥验签
     *
     * @param data
     * @param base64PublicKey
     * @param base64Sign
     * @return
     * @throws Exception
     */

    public static boolean verify(String data, String base64PublicKey, String base64Sign)
            throws Exception {
        byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);

        PublicKey publicKey = string2PublicKey(base64PublicKey);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(publicKey);
        signature.update(dataBytes);

        byte[] signBytes = Base64.decode(base64Sign, Base64.NO_WRAP);
        return signature.verify(signBytes);
    }

    /**
     * 公钥加密
     *
     * @param data
     * @param base64PublicKey
     * @return
     * @throws Exception
     */

    public static String publicEncrypt(String data, String base64PublicKey) throws Exception {
        PublicKey publicKey = string2PublicKey(base64PublicKey);
        Cipher cipher = Cipher.getInstance(PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
        byte[] encryptedData = cipherDofinal(dataBytes, cipher, MAX_ENCRYPT_BLOCK);
        return Base64.encodeToString(encryptedData, Base64.NO_WRAP);
    }

    /**
     * 私钥解密
     *
     * @param base64Data
     * @param base64PrivateKey
     * @return
     * @throws Exception
     */
    public static String privateDecrypt(String base64Data, String base64PrivateKey) throws Exception {
        PrivateKey privateKey = string2PrivateKey(base64PrivateKey);
        Cipher cipher = Cipher.getInstance(PADDING);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        byte[] dataBytes = Base64.decode(base64Data, Base64.NO_WRAP);
        byte[] decryptedData = cipherDofinal(dataBytes, cipher, MAX_DECRYPT_BLOCK);
        return new String(decryptedData, StandardCharsets.UTF_8);
    }

    /**
     * 私钥加密
     *
     * @param data
     * @param base64PrivateKey
     * @return
     * @throws Exception
     */

    public static String privateEncrypt(String data, String base64PrivateKey) throws Exception {
        PrivateKey privateKey = string2PrivateKey(base64PrivateKey);
        Cipher cipher = Cipher.getInstance(PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);

        byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
        byte[] encryptedData = cipherDofinal(dataBytes, cipher, MAX_ENCRYPT_BLOCK);
        return Base64.encodeToString(encryptedData, Base64.NO_WRAP);
    }

    /**
     * 公钥解密
     *
     * @param base64Data
     * @param base64PublicKey
     * @return
     * @throws Exception
     */
    public static String publicDecrypt(String base64Data, String base64PublicKey) throws Exception {
        PublicKey publicKey = string2PublicKey(base64PublicKey);
        Cipher cipher = Cipher.getInstance(PADDING);
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        byte[] dataBytes = Base64.decode(base64Data, Base64.NO_WRAP);
        byte[] decryptedData = cipherDofinal(dataBytes, cipher, MAX_DECRYPT_BLOCK);
        String bb = new String(decryptedData, StandardCharsets.UTF_8);
        return bb;
    }

    /**
     * 将Base64编码后的公钥转换成PublicKey对象
     *
     * @param base64PublicKey
     * @return
     * @throws Exception
     */

    public static PublicKey string2PublicKey(String base64PublicKey) throws Exception {
        byte[] keyBytes = Base64.decode(base64PublicKey,Base64.NO_WRAP);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    /**
     * 将Base64编码后的私钥转换成PrivateKey对象
     *
     * @param base64PrivateKey
     * @return
     * @throws Exception
     */
    public static PrivateKey string2PrivateKey(String base64PrivateKey) throws Exception {
        byte[] keyBytes = Base64.decode(base64PrivateKey,Base64.NO_WRAP);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

    /**
     * 分段处理
     *
     * @param dataBytes
     * @param cipher
     * @param maxBlock
     * @return
     * @throws Exception
     */
    private static byte[] cipherDofinal(byte[] dataBytes, Cipher cipher, int maxBlock)
            throws Exception {
        int inputLen = dataBytes.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > maxBlock) {
                cache = cipher.doFinal(dataBytes, offSet, maxBlock);
            } else {
                cache = cipher.doFinal(dataBytes, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * maxBlock;
        }
        byte[] cipherData = out.toByteArray();
        out.close();
        return cipherData;
    }
}
